from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer
from django.conf import settings


# 加密openid
from users.models import User


def encode_openid(openid):
    # 创建加密对象
    serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=300)

    # 加密数据
    token = serializer.dumps({'openid': openid})
    return token.decode()


# 解密openid
def decode_openid(token):
    serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=300)

    # 解密数据
    try:
        openid = serializer.loads(token).get('openid')
    except Exception as e:
        return None

    return openid


from meiduo_mall.utils import constants


def generate_verify_url(user, email):

    # 准备数据
    user_data = {
        'user_id': user.id,
        'email': email
    }
    serializer = TJWSSerializer(secret_key='settings.SECRET_KEY', expires_in=constants.REDIS_SMS_CODE_EXPIRES)

    # 加密数据
    token = serializer.dumps(user_data).decode()
    # verify_url = 'http://192.168.1.111:8000/verify/email?token=%s' % token
    verify_url = '<a href="http://127.0.0.1:8000/verify/email?token=%s"></a>' % token

    return verify_url


# 解密token
def decode_verify_url(token):
    serializer = TJWSSerializer(secret_key='settings.SECRET_KEY', expires_in=300)
    try:
        user_data = serializer.loads(token)
        user_id = user_data.get('user_id')
        user = User.objects.get(id=user_id)
    except Exception as e:
        print(e)
        return None
    return user